<?php
declare(strict_types=1);

namespace App\Resource\Task;

use App\Order\Model\OrderModel;
use App\Resource\Model\CrontabLog;
use App\Resource\Model\LeaderSorting;
use Carbon\Carbon;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(name="SortingTask", rule="10 22 * * *", callback="task")
 */
class SortingTask
{

    public function task()
    {
        $begin_time = time();
        $tomorrow = Carbon::tomorrow()->toDateString();
        $list = OrderModel::from('store_order as o')->selectRaw("sum(g.number)- sum(g.shop_refund_number)-sum(g.refund_number) as num,o.leader_id,g.goods_id,o.shop_id")
            ->join('store_order_goods as g', 'g.order_no', '=', 'o.order_no')
            ->where(['o.order_source' => 1, 'o.platform_type' => 2, 'o.is_pay' => 1,'o.status'=>3])
            ->whereRaw("CONCAT(DATE_FORMAT(o.create_at, '%Y-'),SUBSTRING(o.appointment_time,4,5))='$tomorrow'")
            ->havingRaw('num > 0')
            ->groupBy(['o.leader_id', 'g.goods_id'])
            ->get()->toArray();
        $date = date('Y-m-d H:i:s');
        $data = [
            'name'=>'SortingTask',
            'time'=>time()-$begin_time,
            'info'=>json_encode($list),
            'status'=>1,
            'job_rule'=>'10 22 * * *',
            'job_desc'=>'每天晚上十点十分执行分拣数量统计',
            'created_at'=>$date
        ];
        if($list){
            foreach ($list as &$value){
                $value['created_at'] = $date;
                $value['status'] = 1;
                $value['sorting_time'] =$tomorrow;

            }
           $res =  LeaderSorting::insert($list);
            $data['time']=time()-$begin_time;
            if($res){

                CrontabLog::insert($data);
            }else{
                $data['status']=0;
                CrontabLog::insert($data);
            }
        }else{
            CrontabLog::insert($data);
        }
    }
}